//
//  ViewController.m
//  OCAppStore
//
//  Created by 王冲 on 2020/1/15.
//  Copyright © 2020 王冲. All rights reserved.
//

#import "ViewController.h"
#import <StoreKit/StoreKit.h>
@interface ViewController ()<SKStoreProductViewControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *button1 = [[UIButton alloc]initWithFrame:CGRectMake(10, 100, 100, 60)];
    [button1 setTitle: @"跳转1" forState: UIControlStateNormal];
    [button1 setBackgroundColor:[UIColor brownColor]];
    [button1 addTarget:self action:@selector(click1) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:button1];
    
    UIButton *button2 = [[UIButton alloc]initWithFrame:CGRectMake(10, 200, 100, 60)];
    [button2 setTitle: @"跳转2" forState: UIControlStateNormal];
    [button2 setBackgroundColor:[UIColor brownColor]];
    [button2 addTarget:self action:@selector(click2) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:button2];
}

- (void)click1 {
    NSURL *url = [NSURL URLWithString:@"itms-apps://itunes.apple.com/app/id1142110895"];
    if (@available(iOS 10.0, *)){
        [[UIApplication sharedApplication]openURL:url options:@{UIApplicationOpenURLOptionsSourceApplicationKey:@YES} completionHandler:^(BOOL success) {
            if (success) {
                NSLog(@"10以后可以跳转url");
            }else{
                NSLog(@"10以后不可以跳转url");
            }
        }];
    }else{
        BOOL success = [[UIApplication sharedApplication]openURL:url];
        if (success) {
            NSLog(@"10以前可以跳转url");
        }else{
            NSLog(@"10以前不可以跳转url");
        }
    }
}

- (void)click2 {
    
    //2:实现代理SKStoreProductViewControllerDelegate
    SKStoreProductViewController *storeProductViewContorller = [[SKStoreProductViewController alloc] init];
    storeProductViewContorller.delegate = self;
    //加载一个新的视图展示
    [storeProductViewContorller loadProductWithParameters: @{SKStoreProductParameterITunesItemIdentifier : @"1142110895"} completionBlock:^(BOOL result, NSError *error) {
        //回调
        if(error){
            NSLog(@"错误%@",error);
        }else{
            //AS应用界面
            [self presentViewController:storeProductViewContorller animated:YES completion:nil];
        }
    }];
}

#pragma mark - 取消按钮监听
//取消按钮监听
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
